package com.questetra.bpms.android;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class WorkitemsJsonParser {
	public List<Workitem> parse(String json) throws JSONException {
		List<Workitem> workitems = new ArrayList<Workitem>();
		JSONObject root = new JSONObject(json);
		JSONArray array = root.getJSONArray("workitems");
		for (int i = 0; i < array.length(); i++) {
			JSONObject object = array.getJSONObject(i);
			Workitem workitem = new Workitem();
			workitem.setId(object.getLong("id"));
			workitem.setTitle(getString(object, "processInstanceTitle"));
			workitem.setProcessModelInfoName(getString(object,
					"processModelInfoName"));
			workitem.setNodeName(getString(object, "nodeName"));
			workitems.add(workitem);
		}
		return workitems;
	}

	/**
	 * @param object
	 * @param key
	 * @return
	 * @throws JSONException
	 */
	private String getString(JSONObject object, String key)
			throws JSONException {
		if (object.isNull(key)) {
			return null;
		}
		return object.getString(key);
	}
}
